﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections;
using System.Runtime.CompilerServices;

namespace RDPRemoteObject
{
    public class BroadCast : MarshalByRefObject, RDPCommon.IBroadCast 
    {
        public static object privateObjectLock = new object();

        static Dictionary<string, RDPCommon.BroadCastEventHandler> 
            m_Dic = new Dictionary<string, RDPCommon.BroadCastEventHandler>();

        [MethodImpl(MethodImplOptions.Synchronized)]
        public object[] BroadCastingInfo(object[] clientIds, string info)
        {
            lock (privateObjectLock)
            {
                object[] rtn = new object[] { 0, null };
                int iSend = 0; //记录发送数量
                foreach (object s in clientIds)
                {
                    if (m_Dic.ContainsKey(s.ToString()))
                    {
                        try
                        {
                            m_Dic[s.ToString()](info);
                            iSend++;
                        }
                        catch (Exception ex)
                        {
                            //统一记入日志
                            RDPCommon.Util.SaveLog(RDPCommon.Util.GetExceptionMsg(ex));
                            m_Dic.Remove(s.ToString());
                        }
                    }
                }
                if (iSend == 0)
                {
                    rtn[0] = 1;
                    rtn[1] = new Exception("暂没有客户端接收您的消息.");
                }
                return rtn;
            }
        }

        public void AddEventReappear(string clientId, RDPCommon.BroadCastEventHandler re)
        {
            lock (privateObjectLock)
            {
                if (!m_Dic.ContainsKey(clientId))
                    m_Dic.Add(clientId, re);
            }
        }

        public void RemoveEventReappear(string clientId, RDPCommon.BroadCastEventHandler re)
        {
            lock (privateObjectLock)
            {
                if (m_Dic.ContainsKey(clientId))
                    m_Dic.Remove(clientId);
            }
        }


        /// <summary>
        /// 将对象的租用周期改变为无限
        /// </summary>
        /// <returns></returns>
        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
